package com.sk.weichat.ui.message;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.githang.statusbar.StatusBarCompat;
import com.sk.weichat.R;
import com.sk.weichat.bean.ChatBgBean;
import com.sk.weichat.bean.Label;
import com.sk.weichat.db.dao.LabelDao;
import com.sk.weichat.downloader.Downloader;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.mucfile.DownManager;
import com.sk.weichat.ui.mucfile.bean.DownBean;
import com.sk.weichat.ui.mucfile.bean.MucFileBean;
import com.sk.weichat.util.ChangeBackgroundHelper;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.JsonCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.sk.weichat.ui.mucfile.DownManager.STATE_DOWNLOADED;
import static com.sk.weichat.ui.mucfile.DownManager.STATE_UNDOWNLOAD;

/**
 * @author lzs
 * @date 2019/9/17
 * Email:343067508@qq.com
 **/
public class ChatBackgroundListActivity extends BaseActivity implements DownManager.DownLoadObserver {
    BaseQuickAdapter<ChatBgBean, BaseViewHolder> adapter;
    List<ChatBgBean> data = new ArrayList<>();
    private String chatID = "";
    ChatBgBean downloadingBean;

    /**
     * @param context
     * @param chatID  群聊传roomid  单聊传friendid
     */
    public static void startChatBackgroundListActivity(Activity context, String chatID, int requestCode) {
        Intent intent = new Intent(context, ChatBackgroundListActivity.class);
        intent.putExtra("chatID", chatID);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_bg_list);
        chatID = getIntent() != null && getIntent().hasExtra("chatID") ? getIntent().getStringExtra("chatID") : "";
        StatusBarCompat.setLightStatusBar(getWindow(), false);
        getSupportActionBar().hide();
        //适配沉浸式
        ImageView ivBack = findViewById(R.id.iv_back);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) ivBack.getLayoutParams();
        lp.height += ScreenUtil.getStatusHeight(mContext);
        ivBack.setLayoutParams(lp);
        ivBack.setPadding(0, ScreenUtil.getStatusHeight(mContext), 0, 0);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setPadding(0, ScreenUtil.getStatusHeight(mContext), 0, 0);
        tvTitle.setText(getString(R.string.select_bg));
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));

        adapter = new BaseQuickAdapter<ChatBgBean, BaseViewHolder>(R.layout.item_chat_bg, data) {

            @Override
            protected void convert(BaseViewHolder holder, ChatBgBean item) {

                holder.addOnClickListener(R.id.iv_bg, R.id.iv_download);
                ImageView ivBackground = holder.getView(R.id.iv_bg);

                ProgressBar progressBar = holder.getView(R.id.progressBar);
                progressBar.setMax((int) item.max);
                progressBar.setProgress((int) item.progress);
                if (item.isChecked) {
                    holder.getView(R.id.iv_check).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.iv_check).setVisibility(View.GONE);
                }
                if (item.progress != 0) {
                    holder.getView(R.id.iv_download).setVisibility(View.GONE);
                    holder.getView(R.id.progressBar).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.iv_download).setVisibility(View.VISIBLE);
                    holder.getView(R.id.progressBar).setVisibility(View.GONE);
                }
                if (item.progress == item.max) {
                    holder.getView(R.id.progressBar).setVisibility(View.GONE);
                    if (item.max != 0) {
                        holder.getView(R.id.iv_download).setVisibility(View.GONE);
                    } else {
                        holder.getView(R.id.iv_download).setVisibility(View.VISIBLE);
                    }
                }
                if (TextUtils.isEmpty(item.getId())) {
                    holder.getView(R.id.iv_download).setVisibility(View.GONE);
                    //默认设置
                    ivBackground.setImageDrawable(new ColorDrawable(Color.WHITE));
                } else {
                    Glide.with(mContext).load(item.getThumbnail()).centerCrop().into(ivBackground);
                }
            }
        };

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ChatBgBean chatBgBean = data.get(position);
                if (TextUtils.isEmpty(chatBgBean.getId())) {
                    //恢复默认设置
                    Intent intent = new Intent();
                    intent.putExtra(ChatBgBean.Parcelable_Key, "");
                    setResult(Activity.RESULT_OK, intent);
                    ToastUtil.showToast(mContext, "设置背景图成功");
                    finish();
                    return;
                }
                MucFileBean bean = toMucFileBean(chatBgBean);
                DownBean downloadBean = DownManager.instance().getDownloadState(bean);
                if (downloadBean.state == STATE_DOWNLOADED) {
                    //下载完成
                    for (int i = 0; i < data.size(); i++) {
                        if (!data.get(i).getId().equals(chatBgBean.getId()) && data.get(i).isChecked) {
                            data.get(i).isChecked = false;
                            adapter.notifyItemChanged(i);
                        }
                    }
                    //使用背景图
                    ChangeBackgroundHelper.useBackgroud(mContext, coreManager.getSelf().getUserId(), chatBgBean.getId());
                    chatBgBean.isChecked = true;
                    adapter.notifyItemChanged(position);
                    Intent intent = new Intent();
                    intent.putExtra(ChatBgBean.Parcelable_Key, DownManager.instance().getFileDir() + "/" + downloadBean.name);
                    setResult(Activity.RESULT_OK, intent);
                    ToastUtil.showToast(mContext, getString(R.string.tips_set_chat_bg_succcess));
                    finish();
                } else if (downloadBean.state == STATE_UNDOWNLOAD) {
                    if (!chatBgBean.isDownloading) {
                        chatBgBean.isDownloading = true;
                        //未下载
                        downloadingBean = chatBgBean;
                        download(bean);
                    }
                }
            }
        });
        recyclerView.setAdapter(adapter);
        getChatBgs();
        DownManager.instance().addObserver(this);
    }

    /**
     * 获取背景图列表
     */
    private void getChatBgs() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().CHAT_BACKGROUND_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<ChatBgBean>(ChatBgBean.class) {
                    @Override
                    public void onResponse(ArrayResult<ChatBgBean> result) {
                        if (result.getResultCode() == 1) {
                            data.clear();
                            ChatBgBean chatBgBean = new ChatBgBean();
                            chatBgBean.isChecked = true;
                            data.add(chatBgBean);
                            //查询下载状态
                            getDownloadState(result.getData());
                            data.addAll(result.getData());
                            setOriginalBackground(data);
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    /**
     * 查询文件的下载状态
     */
    private void getDownloadState(List<ChatBgBean> chatBgBeans) {
        for (int i = 0; i < chatBgBeans.size(); i++) {
            ChatBgBean bgBean = chatBgBeans.get(i);
            DownBean downBean = DownManager.instance().getDownloadState(toMucFileBean(bgBean));
            bgBean.progress = downBean.cur;
            bgBean.max = downBean.max;
        }
    }

    /**
     * 设置原本设置的背景图
     */
    private void setOriginalBackground(List<ChatBgBean> chatBgBeans) {
        String id = ChangeBackgroundHelper.getBackgroundIDByChatID(mContext, chatID);
        //Log.e("lzs", "setOriginalBackground chatID:" + id);
        if (TextUtils.isEmpty(id)) {
            id = ChangeBackgroundHelper.getBackgroundIDByChatID(mContext, ChangeBackgroundHelper.DefaultChatID);
        }
        if (TextUtils.isEmpty(id)) {
            return;
        }
        for (int i = 0; i < chatBgBeans.size(); i++) {
            ChatBgBean bgBean = chatBgBeans.get(i);
            if (bgBean.getId().equals(id)) {
                bgBean.isChecked = true;
            } else {
                bgBean.isChecked = false;
            }
        }
    }

    private MucFileBean toMucFileBean(ChatBgBean chatBgBean) {
        MucFileBean mucFileBean = new MucFileBean();
        mucFileBean.setUrl(chatBgBean.getOriginalgraph());
//        String name = "";
//        try {
//            String url = chatBgBean.getOriginalgraph();
//            name = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
//        } catch (Exception e) {
//            name = System.currentTimeMillis() + chatBgBean.getId();
//        }
        //以图片id作为名称
        mucFileBean.setName(chatBgBean.getId());
        return mucFileBean;
    }

    private void download(MucFileBean image) {
        DownManager.instance().download(image);
    }

    @Override
    public void onDownLoadInfoChange(DownBean info) {
        //Log.e("lzs", "info:" + info.name + "  " + info.cur + "  max:" + info.max);
        ChatBgBean bgBean = findChatBgBean(info.url);
        if (bgBean != null) {
            //刷新进度
            bgBean.max = info.max;
            bgBean.progress = info.cur;
            int index = data.indexOf(bgBean);
            if (bgBean.max == bgBean.progress) {
                //下载完成
                if (downloadingBean != null) {
                    //回调
                    downloadCallBack(downloadingBean.getId());
                }
            }
            adapter.notifyItemChanged(index);
        }
    }

    private ChatBgBean findChatBgBean(String url) {
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getOriginalgraph().equals(url)) {
                return data.get(i);
            }
        }
        return null;
    }

    /**
     * 下载完成回调下载成功
     */
    private void downloadCallBack(String imageID) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("id", imageID);
        params.put("numbserDownloads", "1");
        HttpUtils.get().url(coreManager.getConfig().CHAT_BACKGROUND_LIST_DOWNLOAD_CALLBACK)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {


                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        downloadingBean = null;
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }
}
